package com.hj.aimin.ds.translate;

import com.hj.aimin.ds.annotation.DictTranslate;
import com.hj.aimin.ds.service.DictService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.context.annotation.Lazy;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class DictTranslateInterceptor implements Interceptor {

    private final DictService service;



    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        //1.查询数据
        //2.遍历字段，是否有@DictTranslate注解
        //3.如果有，获取注解参数valueTo
        //4.dict表查询出valueTo的值
        Object result = invocation.proceed();
        if (result instanceof List){
            for (Object object : (List<?>) result
            ) {
                Class<?> clazz = object.getClass();
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field field  : declaredFields
                ) {
                    if(field.isAnnotationPresent(DictTranslate.class)){
                        DictTranslate annotation = field.getAnnotation(DictTranslate.class);
                        String targetFiled = annotation.valueTo();
                        field.setAccessible(true);
                        Object value = field.get(object);
                        Field declaredField = clazz.getDeclaredField(targetFiled);
                        String diceName = service.getById((int) value).getDiceName();
                        declaredField.setAccessible(true);
                        declaredField.set(object,diceName);
                    }
                }
            }
        }

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
